package com.whj.servicepay.controller;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.app.models.AlipayTradeAppPayResponse;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.whj.servicepay.remote.ServiceOrderClient;
import com.whj.servicepay.service.AliPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: wanghaijun
 * @Date: 2023/3/1 - 03 - 01 - 9:23 
 * @Description: com.whj.servicepay.controller
 */

@Controller
@RequestMapping("/alipay")
@ResponseBody
@Slf4j
public class AliPayController {

    @Autowired
    private AliPayService aliPayService;

    /**
     * 调用支付宝支付的功能
     *
     * @param subject 项目名称
     * @param outTradeNo 订单id
     * @param totalAmount 订单金额
     * @return
     */
    @GetMapping("/pay")
    public String pay(String subject,String outTradeNo,String totalAmount){
        AlipayTradePagePayResponse response ;

        try {
            response = Factory.Payment.Page().pay(subject,outTradeNo,totalAmount,"");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
        return response.body;
    }

    @PostMapping("/notify")
    public String notify(HttpServletRequest request) throws Exception {
        log.info("支付宝回调成功！");
        String tradeStatus = request.getParameter("trade_status");

        if(tradeStatus.trim().equals("TRADE_SUCCESS")){
            Map<String,String> param = new HashMap<>();
            Map<String, String[]> parameterMap = request.getParameterMap();
            for (String name : parameterMap.keySet()) {
                param.put(name,request.getParameter(name));
            }
            // 判断得到的参数是支付宝发出的
            if(Factory.Payment.Common().verifyNotify(param)){
                log.info("通过支付宝的验证");

                String outTradeNo = param.get("out_trade_no");
                Long orderId = Long.parseLong(outTradeNo);
                aliPayService.pay(orderId);
            }else {
                log.info("未通过支付宝的验证");
            }
        }
        return "success";
    }
}
